package com.mazha.rabbitmq.controller;

import com.mazha.rabbitmq.pojo.vo.DynamicQueueExchangeVO;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * RabbitMq动态配置
 * 动态生成队列和交换机
 *
 * @author leizi
 * @create 2023-12-03 22:07
 */
@Controller
public class RabbitMqDynamicController {

    /**
     * 实现了AmqpAdmin
     */
    private final RabbitAdmin rabbitAdmin;

    /**
     * 通过AmqpAdmin：创建和删除 Queue，Exchange，Binding
     */
    private final AmqpAdmin amqpAdmin;

    public RabbitMqDynamicController(RabbitAdmin rabbitAdmin, AmqpAdmin amqpAdmin) {
        this.rabbitAdmin = rabbitAdmin;
        this.amqpAdmin = amqpAdmin;
    }

    @PostMapping("/dynamic")
    public void dynamicConfig(DynamicQueueExchangeVO dynamicQueueExchangeVO) {
        //声明mq队列
        Queue newQueue = new Queue(dynamicQueueExchangeVO.getQueueName()
                , dynamicQueueExchangeVO.getDurable()
                , false
                , dynamicQueueExchangeVO.getAutoDelete());
        rabbitAdmin.declareQueue(newQueue);
        //声明交换机
        DirectExchange directExchange = new DirectExchange("direct1_Exchange", true, false);
        rabbitAdmin.declareExchange(directExchange);
        //绑定交换机和队列，并设置Routing key
        Binding binding = BindingBuilder.bind(newQueue).to(directExchange).with(newQueue.getName());
        rabbitAdmin.declareBinding(binding);
    }

    /**
     * 删除mq队列
     *
     * @return
     */
    @PostMapping("/deleteMq")
    public String deleteMq(String mq) {
        rabbitAdmin.deleteQueue(mq);
        return "ok";
    }

    @PostMapping("/")
    public void amqpAdminCreate(){

        // 创建Exchange
        amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));

        /*
        * 创建消息队列
        * - Queue是类可以直接new，构造器第一个参数：队列名，第二参数：是否持久化存在，若没有指定参数则随机给队列名
        * */
        amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true));

        /*
        * 创建绑定规则
        * - 参数1：目的地(队列)
        * - 参数2：绑定的类型->队列
        * - 参数3：Exchange
        * - 参数4：路由件
        * - 参数5：参数没有为null
        * */
        amqpAdmin.declareBinding(new Binding("amqpadmin.queue", Binding.DestinationType.QUEUE,"amqpadmin.exchange","amqp.haha",null));

        //amqpAdmin.deleteExchange();  // 删除交换器
        //amqpAdmin.deleteQueue();  // 删除队列
    }

}
